/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.impl.core.reactor.os;

import com.googlecode.actorom.impl.core.reactor.MessageDemultiplexer;
import com.googlecode.actorom.impl.core.reactor.MessageHandle;
import com.googlecode.actorom.impl.core.reactor.MessageQueue;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.ReentrantLock;
import net.jcip.annotations.ThreadSafe;

/**
 * @author Sergio Bossa
 */
@ThreadSafe
public class OSMessageDemultiplexer implements MessageDemultiplexer {

    private final MessageQueue messageQueue;
    private final Queue<MessageHandle> selectedQueue;
    private final ReentrantLock selectedQueueLock;

    OSMessageDemultiplexer(MessageQueue messageQueue) {
        this.messageQueue = messageQueue;
        selectedQueue = new LinkedList<MessageHandle>();
        selectedQueueLock = new ReentrantLock();
    }

    public void select() throws InterruptedException {
        try {
            selectedQueueLock.lock();
            messageQueue.read(selectedQueue);
        } finally {
            selectedQueueLock.unlock();
        }
    }

    public Queue<MessageHandle> acquireSelectedQueue() {
        selectedQueueLock.lock();
        return selectedQueue;
    }

    public void releaseSelectedQueue() {
        selectedQueueLock.unlock();
    }

    public void wakeUp() {
        messageQueue.interrupt();
    }
}
